﻿using UnityEngine;
using System.Collections;

public class enemyClusterbomb : MonoBehaviour {
	
	private int numberOfClusters = 10;
	private GameObject clusters;
	private GameObject[] clusterList;
	private float mytimer = 0;
	
	public float clusterTime = .8f;
	public float liveTime = 1f;
	public float initialClusterSpeed = 1f;
	public float spawnedClustersForceSpeed = 60f;
	public float spawnRate = 3f;
	public int damageDealt = 25;
	bool startTimer = false;
	
    private GameObject player;
	int i = 0;
	// Use this for initialization
	void Start () 
	{
		liveTime += clusterTime;
		clusters = gameObject;
        player = GameObject.FindGameObjectWithTag("Player");
	}
	
	// Update is called once per frame
    void Update()
    {
        //rigidbody.MovePosition(transform.position);
        rigidbody.MovePosition(transform.position - (transform.position - player.transform.position)* initialClusterSpeed * Time.deltaTime);
        if(startTimer)
			mytimer += Time.deltaTime;
	
        clusterList = GameObject.FindGameObjectsWithTag("cluster");
		//if(mytimer > clusterTime)
		if((transform.position.y - player.transform.position.y < 2f))
		{	
			startTimer = true;
            while( i < numberOfClusters)
            {
                float angle = i * Mathf.PI * 2 / numberOfClusters;
                Vector3 pos = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0) * 1;
                GameObject ClusterRef = Instantiate(clusters, transform.position + pos, Quaternion.Euler(new Vector3(Mathf.Rad2Deg * -angle, 90, 270))) as GameObject; //they all need to be facing in there own forward not a global forward
				Destroy(ClusterRef.GetComponent<enemyClusterbomb>());
				ClusterRef.AddComponent<DealsDamage>();
				ClusterRef.GetComponent<DealsDamage>().DamageOnCollision = damageDealt;
                ClusterRef.rigidbody.AddForce(ClusterRef.transform.forward * spawnedClustersForceSpeed);
                //rigidbody.MovePosition(transform.position + destVector * -rocketSpeed * Time.deltaTime);

                i++;
            }
      			
						renderer.enabled = false;

			//mytimer = 0;
			

		}

          if (mytimer >= liveTime)
			{
	            foreach (GameObject c in clusterList)
	            {
					
	                Destroy(c);
	            }
		    } 
		
	}
}
